package leetcode.hot100;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;

public class Solution56 {

    public static void main(String[] args) {
        int[][] inter = {{1,4},{0,1}};
        new Solution56().fastSort(inter,0,1);
        System.out.println();
    }

    public int[][] merge(int[][] intervals) {

        if(intervals.length<2) return intervals;

        //对左限进行排序，再判断当前区间的开始是否在上一个区间内，如果在，则以最大右限作为新的合并后的右限
        Arrays.sort(intervals, new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                if(o1[0]>o2[0]) return 1;
                return -1;
            }
        });
        ArrayList<int[]> total = new ArrayList<>();
        total.add(intervals[0]);
        for (int i = 1; i < intervals.length; i++) {
            int[] pre = total.get(total.size()-1);
            //由于左边已经排好序，只需比较当前区间左边是否不大于前一个区间右边即可
            if(intervals[i][0]<=pre[1]){
                pre[1] = intervals[i][1]>pre[1]?intervals[i][1]:pre[1];
            }else {
                total.add(intervals[i]);
            }
        }
        return total.toArray(new int[0][]);
    }

    public void fastSort(int[][] arrs, int l, int r){
        if(l >= r) return;
        int i=l, j=r;
        int[] tmp = arrs[l];
        while(i < j){
            while(i<j && arrs[j][0] >= tmp[0]){
                j--;
            }
            arrs[i] = arrs[j];
            while(i<j && arrs[i][0] < tmp[0]){
                i++;
            }
            arrs[j] = arrs[i];
        }
        arrs[i] = tmp;
        fastSort(arrs, l, i-1);
        fastSort(arrs, i+1, r);
    }
}
